import { login, logout, register } from "@/api/login";
import { getToken, setToken, removeToken } from '@/utils/auth'
import hong from '@/assets/images/niejianhong.jpg'
const user = {
    state: {
        token: '',
        name: '',
        avatar: hong,
        roles: [],
        permissions: []
    },
    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        SET_NAME: (state, name) => {
            state.name = name
        },
        SET_AVATAR: (state, avatar) => {
            state.avatar = avatar
        },
        SET_ROLES: (state, roles) => {
            state.roles = roles
        },
        SET_PERMISSIONS: (state, permissions) => {
            state.permissions = permissions
        }
    },
    actions: {
        Login({ commit }, userInfo) {   /*login(username, password)*/
            const username = userInfo.username.trim();
            const password = userInfo.password.trim();
            // const uuid = userInfo.uuid;
            const promise =  new Promise((resolve, reject) => {
               login(username, password).then(res => {
                   if (res.token !== '' && res.token !== undefined){
                       setToken(res.token)  //  后端返回token res.token
                       commit('SET_TOKEN', res.token);
                   }
                   resolve(res);   // 把响应成功的值返回
               }).catch(error => {
                   reject(error)
               })
            })
            return promise;
        },
        Register({ commit }, registerInfo) {
            // const tel = registerInfo.tel; const text01 = registerInfo.text01; const text = registerInfo.text;
            // const digit = registerInfo.digit; const password = registerInfo.password;
            const promise = new Promise((resolve, reject) => {
                register(registerInfo).then(res => {
                    resolve(res);
                }).catch(err => {
                    reject(err);
                })
            })
            return promise;
        },
        // 退出系统
        LogOut({ commit, state }) {
            return new Promise((resolve, reject) => {
                logout(state.token).then(() => {
                    commit('SET_TOKEN', '')
                    commit('SET_ROLES', [])
                    commit('SET_PERMISSIONS', [])
                    removeToken()
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 前端 退出
        FedLogOut({ commit }) {
            return new Promise(resolve => {
                // alert('前端退出，删除token')
                commit('SET_TOKEN', '')
                removeToken()
                resolve()
            })
        }
    }
}


export default user
